package com.emm.yixun.customer.service.impl.app.manage;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.emm.yixun.basic.service.*;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.ProcessInstanceHistoryLog;
import org.activiti.engine.task.Comment;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.mapper.BaseCodeValueMapper;
import com.emm.yixun.common.app.GetSubscribeDetailReqDto;
import com.emm.yixun.common.app.GetSubscribeDetailResDto;
import com.emm.yixun.common.app.servletentity.AnnexListRes;
import com.emm.yixun.common.app.servletentity.CustomerFamilyListRes;
import com.emm.yixun.common.app.servletentity.DealCategoryListReq;
import com.emm.yixun.common.app.servletentity.HistoryTaskInfoListRes;
import com.emm.yixun.common.app.servletentity.ImageListRes;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.BusinessAbnorma;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.FamilyMember;
import com.emm.yixun.common.model.HaveReceiveRefund;
import com.emm.yixun.common.model.Image;
import com.emm.yixun.common.model.NeedReceiveRefund;
import com.emm.yixun.common.model.PriceSchemeDetail;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.TransactionRelation;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.BusinessAbnormaDto;
import com.emm.yixun.common.model.dto.FamilyMemberDto;
import com.emm.yixun.common.model.dto.HaveReceiveRefundDto;
import com.emm.yixun.common.model.dto.ImageDto;
import com.emm.yixun.common.model.dto.NeedReceiveRefundDto;
import com.emm.yixun.common.model.dto.SubscribeDto;
import com.emm.yixun.common.model.dto.TransactionRelationDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.model.enums.BusinessAbnormaEnum;
import com.emm.yixun.common.model.enums.BusinessTypeEnum;
import com.emm.yixun.common.model.enums.CustomerStarEnum;
import com.emm.yixun.common.model.enums.CustomerStatusEnum;
import com.emm.yixun.common.model.enums.DealCategoryEnum;
import com.emm.yixun.common.model.enums.DocTypeEnum;
import com.emm.yixun.common.model.enums.ImgTypeEnum;
import com.emm.yixun.common.model.enums.IntentionLevelEnum;
import com.emm.yixun.common.model.enums.MemberTypeEnum;
import com.emm.yixun.common.model.enums.PaymentMethodEnum;
import com.emm.yixun.common.model.enums.ReceivablesTypeEnum;
import com.emm.yixun.common.model.enums.RelationTypeEnum;
import com.emm.yixun.common.model.enums.RoomStatusEnum;
import com.emm.yixun.common.model.enums.SexEnum;
import com.emm.yixun.common.model.enums.SubscribeBusinessStatusEnum;

@Service("getSubscribeDetailManage")
public class GetSubscribeDetailManage {

	@Autowired
	private CustomerService customerService;
	@Autowired
	private SubscribeService subscribeService;
	@Autowired
	private AuditService auditService;
	@Autowired
	private FamilyMemberService familyMemberService;
	@Autowired
	private BusinessAbnormaService businessAbnormaService;
	@Autowired
	private PriceSchemeDetailService priceSchemeDetailService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private ProjectRoomService projectRoomService;
	@Autowired
	private UserService userService;
	@Autowired
	private TransactionRelationService transactionRelationService;
	@Autowired
	private HaveReceiveRefundService haveReceiveRefundService;
	@Autowired
	private NeedReceiveRefundService needReceiveRefundService;
	@Autowired
	private BaseCodeValueMapper baseCodeValueMapper;
	@Autowired
	private ImageService imageService;
	@Autowired
	private NodeUserService nodeUserService;
	
	DecimalFormat df = new DecimalFormat("#.00");
	
	/**
	 * 认购详情
	 * @param reqDto
	 * @return
	 */
	public GetSubscribeDetailResDto getSubscribeDetail(GetSubscribeDetailReqDto reqDto) {
		GetSubscribeDetailResDto resDto = new GetSubscribeDetailResDto();
		try{
			//1、客户认购详情
			SubscribeDto subscribeDto = new SubscribeDto();
			subscribeDto.setMerchantId(reqDto.getMerchantId());
			if(!"1".equals(reqDto.getIsAudit())){
				subscribeDto.setProjectCode(reqDto.getProjectCode());
			}
			subscribeDto.setId(Long.parseLong(reqDto.getSubscribeId()));
			subscribeDto = subscribeService.getSubscribeDetail(subscribeDto);
			if(subscribeDto == null){
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("无认购详情!");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			if(StringUtils.isNotEmpty(String.valueOf(subscribeDto.getRoomId()))){
				ProjectRoom room = projectRoomService.selectById(subscribeDto.getRoomId());
				if(room != null){
					String roomStatus = room.getRoomStatus();
					//可售或认筹状态可认购
					if(!RoomStatusEnum.VENDIBILITY.getNo().equals(roomStatus) && !RoomStatusEnum.RESERVE.getNo().equals(roomStatus) && AuditStatusEnum.SUCCESS.getNo().equals(subscribeDto.getAuditStatus()) && RoomStatusEnum.SIGN.getNo().equals(roomStatus)){
						resDto.setSubRoomType("0");
						resDto.setSubRoomeMsg("房源暂不可售!");
					}
					//新增设置: 保留状态需判断认购客户是否就是保留客户
					//此功能放二期
				}
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			resDto.setPayDepositId(String.valueOf(subscribeDto.getPayDepositId()));
			resDto.setPayDepositCode(subscribeDto.getPayDepositCode());
			if(subscribeDto.getPayDepositMoney() != null){
				resDto.setPayDepositMoney(String.valueOf(subscribeDto.getPayDepositMoney()));
			}
			resDto.setRoomId(String.valueOf(subscribeDto.getRoomId()));
			ProjectRoom projectRoom = projectRoomService.selectById(subscribeDto
					.getRoomId());
			if (projectRoom == null) {
				resDto.setSubscribeHouses("无");
			} else {
				resDto.setSubscribeHouses(projectRoom.getRoomName());// 认购房源
			}
//			resDto.setSubscribeHouses(subscribeDto.getSubscribeHouses());
			if(subscribeDto.getCalculateArea() != null){
				resDto.setCalculateArea(String.valueOf(subscribeDto.getCalculateArea()));
			}
			if(subscribeDto.getConversionPrice() != null){
				resDto.setDiscountPrice(String.valueOf(subscribeDto.getConversionPrice()));
			}
			if(subscribeDto.getLumpsumPrice() != null){
				/*String discountTotalPrice = df.format(Double.valueOf(String.valueOf(subscribeDto.getLumpsumPrice()))/10000);*/
				String discountTotalPrice = String.valueOf(subscribeDto.getLumpsumPrice());
				resDto.setDiscountTotalPrice(discountTotalPrice);
			}
			if(subscribeDto.getDiscountAmount() != null){
				resDto.setDiscountAmount(String.valueOf(subscribeDto.getDiscountAmount()));
			}
			//业务状态
			String businessStatus = subscribeDto.getBusinessStatus();
			String businessSecStatus = subscribeDto.getBusinessSecStatus();
			resDto.setBusinessStatus(SubscribeBusinessStatusEnum.getByNo(businessStatus).getDes());
			if(StringUtils.isNotBlank(businessSecStatus)){
				if(SubscribeBusinessStatusEnum.REFUNDSUBSCRIPTION.getNo().equals(businessSecStatus)){
					resDto.setBusinessStatus("认购退房");
				}
			}
			//折扣审批状态、折扣审批人、折扣审批时间
			String adp_status = null;
			String nodeName = "";
			List<HistoryTaskInfoListRes> userTaskList = new ArrayList<HistoryTaskInfoListRes>();
			if(subscribeDto.getDiscountApproval() != null && "0".equals(subscribeDto.getDiscountApproval())){
				resDto.setDiscountApproval(subscribeDto.getDiscountApproval());
				resDto.setDiscountApprovalStatus(null);
				resDto.setDiscountApprovalPeople(null);
				resDto.setDiscountApprovalTime(null);
			}else{
				resDto.setDiscountApproval(subscribeDto.getDiscountApproval());
				BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
				businessAbnormaDto.setBusinessId(subscribeDto.getId());//业务ID
				businessAbnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_0.getNo());
				businessAbnormaDto.setOrders(" t.id desc");
				List<BusinessAbnorma> businessAbnormaList = businessAbnormaService.selectListByDto(businessAbnormaDto);
				if(businessAbnormaList.size() > 0){
					for(int i = 0 ;i<businessAbnormaList.size();i++){
						adp_status = businessAbnormaList.get(0).getAuditStatus();
						resDto.setDiscountApprovalStatus(AuditStatusEnum.getByNo(businessAbnormaList.get(0).getAuditStatus()).getDes());//0待提交 1审核中 2已退回 3已通过
						//根据proc_inst_id流程实列ID  获取审批人、审批时间
						List<HistoricActivityInstance> instances = historyService.createHistoricActivityInstanceQuery()
								.processInstanceId(businessAbnormaList.get(0).getProcInstId())
								.orderByHistoricActivityInstanceStartTime().desc().list();
						if (instances != null && instances.size() > 0) {
							boolean isEnd = true;
							userTaskList = new ArrayList<HistoryTaskInfoListRes>();
							for (HistoricActivityInstance historicActivityInstance : instances) {
								if (historicActivityInstance.getEndTime() != null) {// 过滤未审批的数据
									HistoryTaskInfoListRes htf = new HistoryTaskInfoListRes();

									if (historicActivityInstance.getActivityType().equals("startEvent")) {// 开始节点
										ProcessInstanceHistoryLog processInstanceHistoryLog = historyService
												.createProcessInstanceHistoryLogQuery(
														historicActivityInstance.getProcessInstanceId()).singleResult();
										htf.setTaskName("启动");
										htf.setTaskUserName(processInstanceHistoryLog.getStartUserId());
										htf.setTaskCheckStatus("发起");
										htf.setStartDate(historicActivityInstance.getStartTime());
										htf.setEndDate(historicActivityInstance.getEndTime());

										userTaskList.add(htf);
										continue;
									}

									if (historicActivityInstance.getActivityType().equals("endEvent")) {// 结束节点
										continue;
									}

									List<Comment> commentList = taskService.getTaskComments(historicActivityInstance
											.getTaskId());
									htf.setTaskName(historicActivityInstance.getActivityName());
									htf.setStartDate(historicActivityInstance.getStartTime());
									htf.setEndDate(historicActivityInstance.getEndTime());
									if (isEnd)// 为最后一个审批节点
										htf.setIsEnd(isEnd);
									if (null != commentList && commentList.size() > 0)
										htf.setTaskUserName(commentList.get(0).getUserId());//审核人
										htf.setAuditReason(commentList.get(0).getFullMessage());//审核意见
									userTaskList.add(htf);
									isEnd = false;
								}else{
									if(historicActivityInstance.getActivityType().equals("userTask") ) {//审批节点
										User userEntity = userService.selectById(Long.parseLong(historicActivityInstance.getAssignee()));
										nodeName =userEntity.getUserName();
									}
								}
							}

							if (userTaskList.size() > 0) {
								for (HistoryTaskInfoListRes historyTaskInfoVo : userTaskList) {
									if (historyTaskInfoVo.getTaskName().equals("启动")) {// 获取提交时间
//										payDepositDto.setSmTartTime(historyTaskInfoVo.getStartDate());
									}
									// 获取最后的审批人、审批时间、审批意见
									if (historyTaskInfoVo.getIsEnd() != null && historyTaskInfoVo.getIsEnd()) {
										if(AuditStatusEnum.REJECT.getNo().equals(businessAbnormaList.get(0).getAuditStatus()) || AuditStatusEnum.SUCCESS.getNo().equals(businessAbnormaList.get(0).getAuditStatus())){
											UserDto userDto = new UserDto();
											userDto.setUserAccount(historyTaskInfoVo.getTaskUserName());
											User userEntity = userService.selectByDto(userDto);
											resDto.setDiscountApprovalPeople(userEntity.getUserName());//审批人名称
											resDto.setDiscountApprovalTime(sdf.format(historyTaskInfoVo.getEndDate()));//审批时间
										}
									}
								}
							}
						}
					}
				}
			}
			//优惠原因
			if(subscribeDto.getPreferentialReasons() != null){
				resDto.setPreferentialReasons(subscribeDto.getPreferentialReasons());
			}else{
				resDto.setPreferentialReasons(null);
			}
			//新增折扣比例
			if(subscribeDto.getDiscountRate() != null){
				resDto.setAddDiscountRate(String.valueOf(subscribeDto.getDiscountRate()));
//				resDto.setAddDiscountRate(String.valueOf(subscribeDto.getDiscountRate().multiply(new BigDecimal(100))));
			}
			//方案类别（0 低价；1 折扣）
			if(subscribeDto.getFloorType() != null && !"".equals(subscribeDto.getFloorType())){
				resDto.setFloorType(subscribeDto.getFloorType());
			}
			//折后总价
			if(subscribeDto.getDiscountAfterPrice() != null && !"".equals(subscribeDto.getDiscountAfterPrice())){
				resDto.setDiscountAfterAmount(String.valueOf(subscribeDto.getDiscountAfterPrice()));
			}
			
			if("0".equals(subscribeDto.getFloorType())){
				//计算折后总价
				BigDecimal lumpsumPrice = new BigDecimal(0);
				BigDecimal discountAmount = new BigDecimal(0);
				if(null != subscribeDto.getLumpsumPrice()){
					lumpsumPrice = subscribeDto.getLumpsumPrice();
				}
				if(null != subscribeDto.getDiscountAmount()){
					discountAmount = subscribeDto.getDiscountAmount();
				}
				String discountAfterAmount = String.valueOf(lumpsumPrice.subtract(discountAmount));
				resDto.setDiscountAfterAmount(discountAfterAmount);
				
				//折扣比例：房源对应房间折扣比例
				PriceSchemeDetail priceSchemeDetail = priceSchemeDetailService.selectEntityByRoomId(subscribeDto.getRoomId());
				if(priceSchemeDetail != null){
					if(priceSchemeDetail.getDiscountRate() != null && !"".equals(priceSchemeDetail.getDiscountRate())){
						resDto.setDiscountRate(String.valueOf(priceSchemeDetail.getDiscountRate()));
					}else{
						resDto.setDiscountRate(null);
					}
				}
				//JHSong_折扣底价时，从价格方案中获取底价_2016-11-02_代码281~288，注释290
				//resDto.setDiscountRate(String.valueOf(subscribeDto.getDiscountRate()));
			}else{
				//折扣比例：房源对应房间折扣比例
				PriceSchemeDetail priceSchemeDetail = priceSchemeDetailService.selectEntityByRoomId(subscribeDto.getRoomId());
				if(priceSchemeDetail != null){
//					BigDecimal t2 = new BigDecimal(100);
					if(priceSchemeDetail.getDiscountRate() != null && !"".equals(priceSchemeDetail.getDiscountRate())){
						resDto.setDiscountRate(String.valueOf(priceSchemeDetail.getDiscountRate()));
//						resDto.setDiscountRate(String.valueOf(priceSchemeDetail.getDiscountRate().divide(t2)));
					}else{
						resDto.setDiscountRate(null);
					}
				}
			}
			if(subscribeDto.getDiscountNote() != null){
				resDto.setDiscountNote(subscribeDto.getDiscountNote());
			}else{
				resDto.setDiscountNote(null);
			}
			if(subscribeDto.getSubscribePrice() != null){
				resDto.setContractPrice(String.valueOf(subscribeDto.getSubscribePrice()));
			}
			if(subscribeDto.getSubscribeAmount() != null){
				/*String  contractAmount = df.format(Double.valueOf(String.valueOf(subscribeDto.getSubscribeAmount()))/10000);*/
				String  contractAmount = String.valueOf(subscribeDto.getSubscribeAmount());
				resDto.setContractAmount(contractAmount);
			}
			if(subscribeDto.getDepositReceivable() != null){
				resDto.setDepositReceivable(String.valueOf(subscribeDto.getDepositReceivable()));
			}
			if(subscribeDto.getDueTime() != null){
				resDto.setDueTime(sdf.format(subscribeDto.getConversionSignDate()));
			}
			if(StringUtils.isNotEmpty(subscribeDto.getPaymentMethod())){
				resDto.setPaymentMethod(PaymentMethodEnum.getByNo(subscribeDto.getPaymentMethod()).getDes());
			}
			if(StringUtils.isNotEmpty(subscribeDto.getDealCategory())){
				resDto.setDealCategory(DealCategoryEnum.getByNo(subscribeDto.getDealCategory()).getDes());
			}
			//折后金额
			if(subscribeDto.getDiscountAfterPrice() != null && !"".equals(subscribeDto.getDiscountAfterPrice())){
				resDto.setDiscountAfterAmount(String.valueOf(subscribeDto.getDiscountAfterPrice()));
			}
			//推荐人信息
			resDto.setReferenceName(subscribeDto.getReferenceName());
			resDto.setReferenceProportion(String.valueOf(subscribeDto.getReferenceProportion()));
			
			//获取认购客户信息
			Customer customer = customerService.selectById(subscribeDto.getCustomerId());
			resDto.setCustomerName(customer.getCustomerName());
			if(StringUtils.isNotEmpty(customer.getCustomerStar())){
				resDto.setCustomerStar(CustomerStarEnum.getByNo(customer.getCustomerStar()).getDes());
			}else{
				resDto.setCustomerStar(null);
			}
			if(StringUtils.isNotEmpty(customer.getCustomerSex())){
				resDto.setCustomerSex(SexEnum.getByNo(customer.getCustomerSex()).getDes());
			}
			resDto.setCustomerPhone(customer.getCustomerPhone());
			resDto.setCustomerId(customer.getId());
			if(StringUtils.isNotEmpty(customer.getIntentionLevel())){
				resDto.setIntentionLevel(IntentionLevelEnum.getByNo(customer.getIntentionLevel()).getDes());
			}
			if(StringUtils.isNotEmpty(customer.getCustomerOrigin())){
				BaseCodeValue baseCodeValue = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getCustomerOrigin()));
				if(baseCodeValue != null){
					resDto.setCustomerOrigin(baseCodeValue.getCodeName());
				}
			}
			//客户状态
			if(StringUtils.isNotEmpty(customer.getCustomerStatus())){
				resDto.setCustomerStatus(CustomerStatusEnum.getByNo(customer.getCustomerStatus()).getDes());
			}
			if(StringUtils.isNotEmpty(customer.getPeDocumentType())){
				BaseCodeValue baseCodeValue_zjlx = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getPeDocumentType()));
				if(baseCodeValue_zjlx != null){
					resDto.setDocumentType(baseCodeValue_zjlx.getCodeName());
				}
			}
			resDto.setDocumentNumber(customer.getPeDocumentNumber());
			resDto.setMobile(customer.getCustomerPhone());
			resDto.setMailPost(customer.getPeContactAddress());
			resDto.setPostcode(customer.getPePostcode());
			
			if(subscribeDto.getDidTime() != null){
				resDto.setSubscribeDate(sdf.format(subscribeDto.getDidTime()));
			}
			resDto.setRemark(subscribeDto.getRemark());
			resDto.setSubscribeId(String.valueOf(subscribeDto.getId()));
			resDto.setSubscribeCode(subscribeDto.getSubscribeCode());
			if(subscribeDto.getAuditStatus() != null && "0".equals(subscribeDto.getDiscountApproval())  ||  ("1".equals(subscribeDto.getDiscountApproval()) && !"".equals(adp_status) && adp_status != null && adp_status.equals("3"))){
				resDto.setAuditStatus(AuditStatusEnum.getByNo(subscribeDto.getAuditStatus()).getDes());
			}else if("0".equals(subscribeDto.getAuditStatus())){
				resDto.setAuditStatus(AuditStatusEnum.getByNo(subscribeDto.getAuditStatus()).getDes());
			}else if("3".equals(subscribeDto.getAuditStatus()) && StringUtils.isNotEmpty(projectRoom.getRoomStatus()) && "4".equals(projectRoom.getRoomStatus())){
				resDto.setAuditStatus(AuditStatusEnum.getByNo(subscribeDto.getAuditStatus()).getDes());
			}else{
				resDto.setAuditStatus(AuditStatusEnum.getByNo(subscribeDto.getAuditStatus()).getDes());
			}
			if(StringUtils.isNotBlank(subscribeDto.getProcInstId())) {
			//获取最新的审核数据
				List<HistoricActivityInstance> instances = historyService.createHistoricActivityInstanceQuery().processInstanceId(subscribeDto.getProcInstId()).orderByHistoricActivityInstanceStartTime().desc().list();
				if (instances != null && instances.size() > 0) {
					boolean isEnd = true;

					int taskNum = 0;
					userTaskList = new ArrayList<HistoryTaskInfoListRes>();
					for (HistoricActivityInstance historicActivityInstance : instances) {
						if (historicActivityInstance.getEndTime() != null) {// 过滤未审批的数据
							HistoryTaskInfoListRes htf = new HistoryTaskInfoListRes();
	
							if (historicActivityInstance.getActivityType().equals("startEvent")) {// 开始节点
								ProcessInstanceHistoryLog processInstanceHistoryLog = historyService
										.createProcessInstanceHistoryLogQuery(
												historicActivityInstance.getProcessInstanceId()).singleResult();
								htf.setTaskName("启动");
								htf.setTaskUserName(processInstanceHistoryLog.getStartUserId());
								htf.setTaskCheckStatus("发起");
								htf.setStartDate(historicActivityInstance.getStartTime());
								htf.setEndDate(historicActivityInstance.getEndTime());
	
								userTaskList.add(htf);
								continue;
							}

							if (historicActivityInstance.getActivityType().equals("endEvent")) {// 结束节点
								continue;
							}
	
							List<Comment> commentList = taskService.getTaskComments(historicActivityInstance
									.getTaskId());
							htf.setTaskName(historicActivityInstance.getActivityName());
							htf.setStartDate(historicActivityInstance.getStartTime());
							htf.setEndDate(historicActivityInstance.getEndTime());
							if (isEnd)// 为最后一个审批节点
								htf.setIsEnd(isEnd);
							if (null != commentList && commentList.size() > 0)
								htf.setTaskUserName(commentList.get(0).getUserId());//审核人
								htf.setAuditReason(commentList.get(0).getFullMessage());//审核意见
							userTaskList.add(htf);
							isEnd = false;
						}else{
							if(historicActivityInstance.getActivityType().equals("userTask") ) {//审批节点
								User userEntity = userService.selectById(Long.parseLong(historicActivityInstance.getAssignee()));
								nodeName =userEntity.getUserName();
//								if(taskNum > 0){
//									nodeName = nodeName + "下一审批人："+userEntity.getUserName();
//								}
//								taskNum ++;
							}
						}
					}
	
					if (userTaskList.size() > 0) {
						for (HistoryTaskInfoListRes historyTaskInfoVo : userTaskList) {
							if (historyTaskInfoVo.getTaskName().equals("启动")) {// 获取提交时间
	//							payDepositDto.setSmTartTime(historyTaskInfoVo.getStartDate());
							}
							// 获取最后的审批人、审批时间、审批意见
							if (historyTaskInfoVo.getIsEnd() != null && historyTaskInfoVo.getIsEnd()) {
									UserDto userDto = new UserDto();
									userDto.setUserAccount(historyTaskInfoVo.getTaskUserName());
									User userEntity = userService.selectByDto(userDto);
									if(userEntity != null) {
										resDto.setAuditId(userEntity.getUserName());//审批人名称
										resDto.setAuditTime(sdf.format(historyTaskInfoVo.getEndDate()));//审批时间
										resDto.setAuditReason(historyTaskInfoVo.getAuditReason());//审批意见
									}
								}
							}
						}
					}
			}
			//获取成交类别List
			TransactionRelationDto transactionRelationDto = new TransactionRelationDto(); 
			transactionRelationDto.setBusinessId(subscribeDto.getId());
			transactionRelationDto.setRelationType(RelationTypeEnum.SUBSCRIBE.getNo());
			//transactionRelationDto.setUserCode(subscribeDto.getUserCode());
			List<TransactionRelation> transactionRelationList = transactionRelationService.selectListByDto(transactionRelationDto);
			List<DealCategoryListReq> dealCategoryList  = new ArrayList<DealCategoryListReq>();
			if(transactionRelationList.size() > 0){
				for(int r=0;r<transactionRelationList.size();r++){
					DealCategoryListReq dealCategoryListReq = new DealCategoryListReq();
					dealCategoryListReq.setRelationAgentId(String.valueOf(transactionRelationList.get(r).getRelationAgentid()));
					User user_agent = userService.selectById(transactionRelationList.get(r).getRelationAgentid());
					dealCategoryListReq.setRelationAgentName(user_agent.getUserName());
					dealCategoryListReq.setProportionCommission(transactionRelationList.get(r).getProportionCommission());
					dealCategoryList.add(dealCategoryListReq);
				}
				resDto.setDealCategoryList(dealCategoryList);
			}else{
				DealCategoryListReq dealCategoryListReq = new DealCategoryListReq();
				UserDto userDto = new UserDto();
				userDto.setUserCode(subscribeDto.getUserCode());
				User user_agent = userService.selectByDto(userDto);
				dealCategoryListReq.setProportionCommission("100");
				dealCategoryListReq.setRelationAgentId(String.valueOf(user_agent.getId()));
				dealCategoryListReq.setRelationAgentName(user_agent.getUserName());
				dealCategoryList.add(dealCategoryListReq);
				resDto.setDealCategoryList(dealCategoryList);
			}
			
			//已收认筹金或认购金
			 if(subscribeDto.getId() != null && !"".equals(subscribeDto.getId())){
				HaveReceiveRefundDto entity = new HaveReceiveRefundDto();
				entity.setRelationId(subscribeDto.getId());
				entity.setReceivablesType(ReceivablesTypeEnum.SUBSCRIBE.getNo());
				//金额被转之后，继续入参是否转，会导致认购方面查不到已收金额。
				//JHSong_2016-10-26_操作： 注释
//				entity.setTransferStatus(TransferStatusEnum.NORMAL.getNo());
//				entity.setDocType(DocTypeEnum.COLLECTION.getNo());
				List<HaveReceiveRefund> resList = haveReceiveRefundService.selectListByDto(entity);
				BigDecimal realAmount = new BigDecimal("0");
				if(resList.size() > 0){
					for(int i = 0; i < resList.size(); i++){
						HaveReceiveRefund have = (HaveReceiveRefund)resList.get(i);
						realAmount = realAmount.add(have.getRealAmount());
					}
					resDto.setRealAmount(String.valueOf(realAmount));
					resDto.setBusReturnType("2");
				}else{
					if(subscribeDto.getPayDepositId() != null && !"".equals(subscribeDto.getPayDepositId())){
						HaveReceiveRefundDto entity2 = new HaveReceiveRefundDto();
						entity2.setRelationId(subscribeDto.getPayDepositId());
						entity2.setReceivablesType(ReceivablesTypeEnum.DEPOSIT.getNo());
						//金额被转之后，继续入参是否转，会导致认购方面查不到已收金额。
						//JHSong_2016-10-26_操作： 注释
//						entity2.setTransferStatus(TransferStatusEnum.NORMAL.getNo());
//						entity2.setDocType(DocTypeEnum.COLLECTION.getNo());
						List<HaveReceiveRefund> resList2 = haveReceiveRefundService.selectListByDto(entity2);
						BigDecimal realAmount2 = new BigDecimal("0");
						if(resList2.size() > 0){
							for(int i = 0; i < resList2.size(); i++){
								HaveReceiveRefund have2 = (HaveReceiveRefund)resList2.get(i);
								realAmount2 = realAmount2.add(have2.getRealAmount());
							}
						}
						resDto.setRealAmount(String.valueOf(realAmount2));
						resDto.setBusReturnType("1");
					}else{
						resDto.setRealAmount(null);
					}
				}
			 }
			
			//2、获取家庭成员
			FamilyMemberDto fmDto = new FamilyMemberDto();
			fmDto.setBuyId(subscribeDto.getId());
			fmDto.setCustomerId(subscribeDto.getCustomerId());
			fmDto.setMemberType(MemberTypeEnum.SUBSCRIBE.getNo());
			List<FamilyMember> fmList = familyMemberService.selectListByDto(fmDto);
			List<CustomerFamilyListRes> customerFamilyList = new ArrayList<CustomerFamilyListRes>();
			for(FamilyMember fm: fmList){
				CustomerFamilyListRes cflRes = new CustomerFamilyListRes();
				cflRes.setMemberName(fm.getMemberName());
				if(StringUtils.isNotEmpty(fm.getDocumentType())){
					BaseCodeValue baseCodeValue_jtcy_zjlx = baseCodeValueMapper.selectEntityById(Long.valueOf(fm.getDocumentType()));
					if(baseCodeValue_jtcy_zjlx != null){
						cflRes.setDocumentType(baseCodeValue_jtcy_zjlx.getCodeName());
					}
				}
				cflRes.setDocumentNumber(fm.getDocumentNumber());
				cflRes.setMobile(fm.getMobile());
				customerFamilyList.add(cflRes);
			}
			
			// 图片列表
			ImageDto imageDto = new ImageDto();
			imageDto.setMerchantId(subscribeDto.getMerchantId());
			imageDto.setUserCode(subscribeDto.getUserCode());
			imageDto.setObjectId(subscribeDto.getId());
			imageDto.setImgType(ImgTypeEnum.SUBSCRIBE.getNo());
			List<Image> imageList = imageService.selectListByDto(imageDto);
			List<ImageListRes> imageListRes = new ArrayList<ImageListRes>();
			List<AnnexListRes> annexListRes = new ArrayList<AnnexListRes>();
			if (imageList.size() > 0) {
				int annexNum = 0;
				for (Image image : imageList) {
					//gif|jpg|jpeg|png|bmp|GIF|JPG|JPEG|PNG|BMP图片后缀名格式
					String url_format = image.getSmallUrl();
					String url = url_format.substring(url_format.length()-3);
					String url2 = url_format.substring(url_format.length()-4);
					if("gif".equals(url) || "GIF".equals(url) || "jpg".equals(url) || "JPG".equals(url) 
						|| "png".equals(url) || "PNG".equals(url) || "bmp".equals(url) 
						|| "BMP".equals(url) || "jpeg".equals(url2) || "JPEG".equals(url2)){
						ImageListRes imageEntity = new ImageListRes();
						imageEntity.setImageId(String.valueOf(image.getId()));
						imageEntity.setTitle(image.getTitle());
						imageEntity.setLargeUrl(image.getLargeUrl());
						imageEntity.setNormalUrl(image.getNormalUrl());
						imageEntity.setSmallUrl(image.getSmallUrl());
						imageListRes.add(imageEntity);						
					}else{
						annexNum += 1;
						AnnexListRes annexEntity = new AnnexListRes();
						annexEntity.setAnnexName(image.getTitle());
						annexListRes.add(annexEntity);
					}
				}
				resDto.setAnnexNum(String.valueOf(annexNum));
				resDto.setAnnexList(annexListRes);
				resDto.setImageList(imageListRes);
			} else {
				resDto.setImageList(null);
			}
			
			//校验认筹金是否已经收满
			NeedReceiveRefundDto nrrDto = new NeedReceiveRefundDto();
			nrrDto.setRelationId(Long.parseLong(reqDto.getSubscribeId()));
			nrrDto.setBusinessType(BusinessTypeEnum.SUBSCRIBE.getNo());
			nrrDto.setDocType(DocTypeEnum.COLLECTION.getNo());
			NeedReceiveRefund need = needReceiveRefundService.selectByDto(nrrDto);
			if(need != null){
				BigDecimal big = new BigDecimal("0");
				HaveReceiveRefundDto entity = new HaveReceiveRefundDto();
				entity.setReceivablesId(need.getId());
				List<HaveReceiveRefund> list = haveReceiveRefundService.selectListByDto(entity);
				for (HaveReceiveRefund refund : list) {
					big = big.add(refund.getRealAmount());
				}
				if(big.compareTo(need.getTotalReceivablesAmount()) != 0){
					resDto.setEnough("0");
				}else{
					resDto.setEnough("1");
				}
			}
//			NeedReceiveRefundDto nrrDto = new NeedReceiveRefundDto();
//			if(subscribeDto.getPayDepositId() != null && !"".equals(subscribeDto.getPayDepositId())){
//				nrrDto.setRelationId(subscribeDto.getPayDepositId());
//				nrrDto.setBusinessType(BusinessTypeEnum.DEPOSIT.getNo());
//				nrrDto.setDocType(DocTypeEnum.COLLECTION.getNo());
//				NeedReceiveRefund need = needReceiveRefundService.selectByDto(nrrDto);
//				if(need != null){
//					BigDecimal big = new BigDecimal("0");
//					HaveReceiveRefundDto entity = new HaveReceiveRefundDto();
//					entity.setReceivablesId(need.getId());
//					List<HaveReceiveRefund> list = haveReceiveRefundService.selectListByDto(entity);
//					for (HaveReceiveRefund refund : list) {
//						big = big.add(refund.getRealAmount());
//					}
//					if(big.compareTo(need.getTotalReceivablesAmount()) != 0){
//						resDto.setEnough("0");
//					}else{
//						resDto.setEnough("1");
//					}
//				}
//			}
			
			resDto.setCustomerFamilyList(customerFamilyList);
			resDto.setNodeName(nodeName);
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		}catch(Exception e){
			e.printStackTrace();
			resDto = new GetSubscribeDetailResDto();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("认购详情获取失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}
}


